import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { ReportingService } from '../../services/reporting.service';
import { DatatableReportingFundInfoComponent } from '../fund-info/fund-info.component';

@Component({
  selector: 'app-datatable-fund-reporting',
  templateUrl: './fund-reporting.component.html',
  styleUrls: ['../../../../commom/less/commom-table.less','./fund-reporting.component.less']
})
export class DatatableFundReportingComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];
  tabType!: string;
  tabs: any[] = [
    { name: '待上传', value: '1' },
    { name: '上传中', value: '2' },
    { name: '已上传', value: '3' },
    { name: '异常', value: '4' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '1'; //选择的项目
  serviceTel = '';
  selectedRows: any[] = [];
  netWorkList: any[] = [{
    enterpriseName:'全部', id: ''
  }];

  isLoading: boolean = false;
  constructor(
    public service: ReportingService,
    private router: Router,
    private ar: ActivatedRoute,
    private modal: NzModalService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
    this.sfValue = { ltdId: '1516592797585588226', };
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {}, {
      uploadStatus: this.selectedIndex
    });
    delete params._$expand;
    return { ...params };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { listSource: 1 });
    if (this.sfValue) {
      Object.assign(requestOptions.body, {
        ...this.sfValue,
        uploadStatus: this.selectedIndex
      });
    }
    // this.loadingList = true;
    return requestOptions;
  };

  dataProcess = (data: STData[]): STData[] => {
    // this.loadingList = false;
    return data;
  };

  /**
   * 选中行
   */
  // get selectedRows() {
  //   return this.st?.list.filter((item: any) => item.checked) || [];
  // }

  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
    this.service.request(this.service.$api_get_network_freight_forwarder_list, {}).subscribe((res:any) => {
      console.log(res);
      this.netWorkList.push(...res)
    })
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        orderCode: { title: '订单号', type: 'string', ui: { placeholder: '请输入' } },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        serialNumberCode: {
          type: 'string',
          title: '流水单号',
          ui: {
            placeholder: '请输入'
          }
        },
        carrier: {
          title: '承运司机',
          type: 'string',
          ui: {
            placeholder: '请输入司机姓名'
          }
        },
        carNumber: {
          title: '车牌号',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入'
          }
        },
        payee: {
          title: '车队长',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入'
          }
        },
        // uploadStatus: {
        //   title: '上传状态',
        //   type: 'string',
        //   enum: [
        //     { label: '待上传', value: 0 },
        //     { label: '已上传', value: 1 },
        //     { label: '异常', value: 2 }
        //   ],
        //   ui: {
        //     placeholder: '请选择',
        //     widget: 'select',
        //     allowClear: true,
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //   }
        // },
        verifyStatus: {
          title: '本地校验',
          type: 'string',
          enum: [
            { label: '检测中', value: '0' },
            { label: '通过', value: '1' },
            { label: '不通过', value: '2' }
          ],
          ui: {
            placeholder: '请选择',
            allowClear: true,
            widget: 'select'
          }
        },
        ltdId: {
          title: '网络货运人',
          type: 'string',
          ui: {
            placeholder: '请选择',
            widget: 'select',
            asyncData: () => this.service.getNetworkFreightForwarder({}, false),
            allowClear: true
          },
          default: '1516592797585588226'
        },
        transactionTime: {
          title: '交易时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        uploadTime: {
          title: '上传时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        // orderPayTime: {
        //   title: '核销时间',
        //   type: 'string',
        //   ui: {
        //     widget: 'sl-from-to',
        //     type: 'date',
        //     format: 'yyyy-MM-dd'
        //   } as SFDateWidgetSchema
        // },
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '上传状态', render: 'uploadStatus', className: 'text-center', width: '120px' },
      { title: '本地校验', render: 'verifyStatus', className: 'text-center', width: '120px' },
      { title: '流水单号', index: 'serialNumberCode', className: 'text-center', width: '190px' },
      {
        title: '订单号',
        render: 'orderCode',
        className: 'text-center',
        width: '180px'
      },
      { title: '运单号', render: 'wayBillCode', className: 'text-center', width: '180px' },
      {
        title: '网络货运人',
        index: 'ltdName',
        className: 'text-center',
        width: '180px'
      },
      { title: '实际承运人名称', index: 'carrier', className: 'text-center', width: '150px' },
      { title: '实际承运人证件号码', index: 'cardId', className: 'text-center', width: '200px' },
      { title: '车牌号', index: 'carNumber', className: 'text-center', width: '180px' },
      { title: '车牌颜色', index: 'carColorLabel', className: 'text-center', width: '180px' },
      { title: '总金额', render: 'tolalAmount', className: 'text-center', width: '120px' },

      { title: '付款方式', index: 'payType', className: 'text-center', width: '150px' },
      { title: '车队长', index: 'payee', className: 'text-center', width: '150px' },
      { title: '收款账户', index: 'collectionAccount', className: 'text-center', width: '180px' },

      { title: '收款银行', index: 'bankTypeLabel', className: 'text-center', width: '150px' },

      { title: '银行流水号', index: 'bankSerialNumber', className: 'text-center', width: '180px' },
      { title: '实际支付金额', render: 'payAmount', className: 'text-center', width: '150px' },
      { title: '交易时间', index: 'transactionTime', className: 'text-center', width: '180px' },
      { title: '上传次数', index: 'uploadFrequency', className: 'text-center', width: '120px' },
      { title: '上传时间', index: 'uploadTime', className: 'text-center', width: '180px' }
    ];
  }

  /**
   *撤销
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要撤回的数据');
      return;
    }
    this.modal.confirm({
      nzTitle: '撤回提示',
      nzContent: ' 撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        const ids = this.selectedRows.map(i => i?.id);
        this.service.request(this.service.$api_fund_reporting_recall, ids).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');

            this.search();
          }
        });
      }
    });
  }

  selectChange(item: any) {
    this.selectedIndex = item?.value || '';

    setTimeout(() => {
      this.selectedRows = [];
      this.st.load(1);
    });
  }

  /**
   * 查看当行数据
   */
  view(record: STData) {
    // this.router.navigate(['../view', record.uuid], { relativeTo: this.ar });
    this.router.navigate(['../detail'], {
      queryParams: {
        id: record.id
      },
      relativeTo: this.ar
    });
  }

  // appeal(item: any) {
  //   const modalRef = this.modal.create({
  //     nzTitle: '申诉',
  //     nzWidth: '40%',
  //     nzContent: CtcAppealComponent,
  //     nzComponentParams: {
  //       i: item,
  //       status: 'add'
  //     },
  //     nzFooter: null
  //   });
  //   modalRef.afterClose.subscribe(res => {
  //     if (res) {
  //       this.search({ representationsStatus: '' });
  //     }
  //   })
  // }

  /**
   * 上传
   */
  upload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要上传的数据');
      return;
    }
    let status = true;
    this.selectedRows.forEach((i:any) => {
      if(i?.billPutStatus == '1') {
        status = false
      }
    })
    if(!status) {
      this.openWainingModal('已上传的数据不能再次上传！');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_fund_reporting_upload, ids).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('上传成功');
        this.search();
      }
    });
  }

  /**
   * 查看校验结果
   */
  viewResult(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '校验结果',
      nzWidth: 1200,

      nzContent: DatatableReportingFundInfoComponent,
      nzComponentParams: {
        record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {});
  }

  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    if (record?.verifyStatus !== '2') {
      return;
    }
    this.openWainingModal('监管审核结果', record?.uploadResult);
  }

  /**
   * 更新数据
   */
  updateData() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要更新的数据');
      return;
    }
    let status = true;
    this.selectedRows.forEach((i:any) => {
      if(i?.billPutStatus == '1') {
        status = false
      }
    })
    if(!status) {
      this.openWainingModal('已上传的数据不能更新！');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_update_fund_data, ids).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('更新成功');
        this.selectedRows = [];
        this.st.reload();
      }
    });
  }

  search() {
    this.selectedRows = [];
    this.st.load(1);
  }

  /**
   * 异步导出
   */
  export() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_export_fund_reporting);
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content
    });
  }

  changeSt(e: STChange): void {
    if (e.type === 'checkbox') {
      const checkRows = (e.checkbox as STData[]) || [];
      //判断当前页是否有选中的行
      if (checkRows.length === 0) {
        // 当前页没有存在已勾选的行，移除之前所记录的当前页的行
        const stList = this.st.list;
        stList.forEach(item => {
          this.selectedRows = this.selectedRows.filter((e: any) => e.id !== item.id);
        });
      } else {
        //添加新增的行
        checkRows.forEach((item: any) => {
          const newSelectedList = this.selectedRows.filter((r: any) => r.id === item.id);
          if (newSelectedList.length === 0) {
            this.selectedRows.push(item);
          }
        });
        // 移除取消选中的行
        const stList = this.st.list;
        stList.forEach(item => {
          if (!item.checked) {
            const index = this.selectedRows.findIndex(_item => item.id === _item.id);
            if (index !== -1) this.selectedRows.splice(index, 1);
          }
        });
      }
    } else if (e.type === 'loaded') {
      // 页面加载时勾选
      (e?.loaded || []).forEach((r: any) => {
        this.selectedRows.forEach(x => {
          if (x.id === r.id) {
            r.checked = true;
          }
        });
      });
    }
  }

  routeToOrder(item: any) {
    if (item.orderType === '1') {
      window.open(location.origin + `/#/order-management/vehicle/vehicle-detail/${item.orderId}`);
    } else if (item.orderType === '2') {
      window.open(location.origin + `/#/order-management/bulk/bulk-detail/${item.orderId}`);
    } else if (item.orderType === '3') {
      this.router.navigate(['/order-management/vehicle/vehicle-detail/' + item.orderId]);
    }
  }

  routeTowaybill(item: any) {
    if (item.orderType === '1') {
      window.open(location.origin + `/#/waybill-management/vehicle/vehicle-detail/${item.wayBillId}`);
    } else if (item.orderType === '2') {
      window.open(location.origin + `/#/waybill-management/bulk/bulk-detail/${item.wayBillId}`);
    } else if (item.orderType === '3') {
      window.open(location.origin + `/#/waybill-management/vehicle/vehicle-detail/${item.wayBillId}`);
    }
  }
}
